package com.jiuwei.mylibrary.utils

import android.app.Activity

/**
 * Activity管理器，用于管理所有Activity实例
 */
object ActivityManager {
    private val activityList = mutableListOf<Activity>()

    /**
     * 添加Activity到管理器
     */
    fun addActivity(activity: Activity) {
        activityList.add(activity)
    }

    /**
     * 从管理器中移除Activity
     */
    fun removeActivity(activity: Activity) {
        activityList.remove(activity)
    }

    /**
     * 关闭所有Activity
     */
    fun finishAllActivities() {
        for (activity in activityList) {
            if (!activity.isFinishing) {
                activity.finish()
            }
        }
        activityList.clear()
    }

    /**
     * 关闭指定类型的Activity
     */
    fun finishActivity(activityClass: Class<out Activity>) {
        val iterator = activityList.iterator()
        while (iterator.hasNext()) {
            val activity = iterator.next()
            if (activity.javaClass == activityClass) {
                if (!activity.isFinishing) {
                    activity.finish()
                }
                iterator.remove()
            }
        }
    }

    /**
     * 获取当前Activity（栈顶Activity）
     */
    fun getCurrentActivity(): Activity? {
        return if (activityList.isNotEmpty()) {
            activityList.last()
        } else {
            null
        }
    }

    /**
     * 获取所有Activity列表
     */
    fun getActivityList(): List<Activity> {
        return activityList
    }
}